<template>
  <div class="container">
    <Breadcrumb :items="['运营商管理', '客户预存']" />
    <a-card class="general-card" :title="$t('客户预存管理')">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="searchForm"
            label-align="left"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-layout="inline"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="partnerId" :label="$t('运营商')">
                  <a-select
                    v-model="searchForm.partnerId"
                    :placeholder="$t('请选择运营商')"
                    :loading="partnerLoading"
                    allow-clear
                  >
                    <a-option
                      v-for="partner in partnerOptions"
                      :key="partner.id"
                      :value="partner.id"
                      :label="partner.partnerName"
                    >
                      {{ partner.partnerName }}
                    </a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="incomeStatus" :label="$t('状态')">
                  <a-select
                    v-model="searchForm.incomeStatus"
                    :placeholder="$t('请选择状态')"
                    allow-clear
                  >
                    <a-option :value="IncomeStatusEnum.PENDING">待审核</a-option>
                    <a-option :value="IncomeStatusEnum.APPROVED">已通过</a-option>
                    <a-option :value="IncomeStatusEnum.REJECTED">已拒绝</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="timeRange" :label="$t('时间范围')">
                  <a-range-picker
                    v-model="timeRange"
                    style="width: 100%"
                    show-time
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="16">
                <a-space>
                  <a-button type="primary" @click="search">
                    <template #icon>
                      <icon-search />
                    </template>
                    {{ $t('搜索') }}
                  </a-button>
                  <a-button @click="reset">
                    <template #icon>
                      <icon-refresh />
                    </template>
                    {{ $t('重置') }}
                  </a-button>
                  <a-button type="primary" status="success" @click="openAddForm">
                    <template #icon>
                      <icon-plus />
                    </template>
                    {{ $t('新增预存') }}
                  </a-button>
                  <a-button type="primary" status="warning" @click="openConsumeForm">
                    <template #icon>
                      <icon-minus />
                    </template>
                    {{ $t('预存消费') }}
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
      </a-row>
      
      <!-- 预存总金额统计 -->
      <a-row class="summary-row">
        <a-col :span="24">
          <a-statistic 
            title="累计预存总金额" 
            :value="depositSum" 
            :precision="2" 
            show-group-separator 
            :value-style="{color: '#1677ff'}"
          >
            <template #prefix>¥</template>
          </a-statistic>
        </a-col>
      </a-row>
      
      <a-divider style="margin-top: 0" />
      
      <a-table
        row-key="id"
        :loading="loading"
        :data="renderData"
        :pagination="pagination"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
        :bordered="false"
      >
        <template #columns>
          <a-table-column title="运营商" data-index="partnerName" />
          <a-table-column title="金额" data-index="incomeAmount">
            <template #cell="{ record }">
              <span :style="{ color: record.incomeAmount >= 0 ? '#52c41a' : '#f5222d' }">
                {{ formatPrice(record.incomeAmount) }}
              </span>
            </template>
          </a-table-column>
          <a-table-column title="订单号" data-index="sn">
            <template #cell="{ record }">
              {{ record.sn || '-' }}
            </template>
          </a-table-column>
          <a-table-column title="备注" data-index="remark">
            <template #cell="{ record }">
              {{ record.remark || '-' }}
            </template>
          </a-table-column>
          <a-table-column title="操作人" data-index="createBy">
            <template #cell="{ record }">
              {{ record.createBy || '-' }}
            </template>
          </a-table-column>
          <a-table-column title="状态" data-index="incomeStatus">
            <template #cell="{ record }">
              <a-tag 
                :color="
                  record.incomeStatus === IncomeStatusEnum.PENDING 
                  ? 'green' 
                  : record.incomeStatus === IncomeStatusEnum.APPROVED
                  ? 'blue' 
                  : 'red'
                "
              >
                {{ getStatusName(record.incomeStatus) }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="创建时间" data-index="createTime">
            <template #cell="{ record }">
              {{ formatDateTime(record.createTime) }}
            </template>
          </a-table-column>
          <a-table-column title="操作" fixed="right" :width="200">
            <template #cell="{ record }">
              <a-space>
                <a-button 
                  v-if="record.incomeStatus === IncomeStatusEnum.PENDING" 
                  type="text" 
                  size="small" 
                  status="success"
                  @click="handleAudit(record, IncomeStatusEnum.APPROVED)"
                >
                  通过
                </a-button>
                <a-button 
                  v-if="record.incomeStatus === IncomeStatusEnum.PENDING" 
                  type="text" 
                  size="small" 
                  status="danger"
                  @click="handleAudit(record, IncomeStatusEnum.REJECTED)"
                >
                  拒绝
                </a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 新增预存表单对话框 -->
    <a-modal
      v-model:visible="addFormVisible"
      title="新增预存"
      @before-ok="handleSubmitForm"
      @cancel="closeForm"
    >
      <deposit-form ref="addFormRef" @submit="handleSubmitForm" />
    </a-modal>

    <!-- 预存消费表单对话框 -->
    <a-modal
      v-model:visible="consumeFormVisible"
      title="预存消费"
      @before-ok="handleSubmitConsumeForm"
      @cancel="closeForm"
    >
      <deposit-form ref="consumeFormRef" :is-consume="true" @submit="handleSubmitConsumeForm" />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import { 
  getPartnerList, 
  Partner
} from '@/api/partner';
import { 
  getPartnerIncomeList, 
  getPartnerIncomeSum,
  addPartnerDeposit,
  consumePartnerDeposit,
  auditPartnerIncome,
  PartnerIncome,
  IncomeStatusEnum,
  IncomeTypeEnum
} from '@/api/partner/income';
import dayjs from 'dayjs';
import { 
  IconSearch, 
  IconRefresh, 
  IconPlus, 
  IconMinus
} from '@arco-design/web-vue/es/icon';
import DepositForm from './components/deposit-form.vue';

const { loading, setLoading } = useLoading();
const renderData = ref<PartnerIncome[]>([]);
const addFormRef = ref();
const consumeFormRef = ref();
const addFormVisible = ref(false);
const consumeFormVisible = ref(false);
const partnerLoading = ref(false);
const partnerOptions = ref<Partner[]>([]);
const depositSum = ref(0);

const timeRange = ref<[Date, Date] | undefined>(undefined);

const searchForm = reactive({
  partnerId: undefined as number | undefined,
  incomeStatus: undefined as number | undefined,
  startTime: undefined as string | undefined,
  endTime: undefined as string | undefined,
});

const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
});

// 格式化日期时间
function formatDateTime(date: string | undefined) {
  if (!date) return '-';
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
}

// 格式化金额
function formatPrice(price: number | undefined) {
  if (price === undefined || price === null) return '¥0.00';
  return `¥${price.toFixed(2)}`;
}

// 获取状态名称
function getStatusName(status: number) {
  switch (status) {
    case IncomeStatusEnum.PENDING:
      return '待审核';
    case IncomeStatusEnum.APPROVED:
      return '已通过';
    case IncomeStatusEnum.REJECTED:
      return '已拒绝';
    default:
      return '未知状态';
  }
}

// 查询数据
async function fetchData() {
  setLoading(true);
  try {
    const params = {
      ...searchForm,
      current: pagination.current,
      size: pagination.pageSize,
    };
    
    const res = await getPartnerIncomeList(params);
    renderData.value = res.data.records;
    pagination.total = res.data.total;
  } catch (err) {
    console.error('获取预存记录列表出错:', err);
    Message.error('获取预存记录列表失败');
  } finally {
    setLoading(false);
  }
}

// 获取预存总金额
async function fetchDepositSum() {
  try {
    const params = {
      partnerId: searchForm.partnerId,
      startTime: searchForm.startTime,
      endTime: searchForm.endTime,
    };
    
    const res = await getPartnerIncomeSum(params);
    depositSum.value = res.data;
  } catch (err) {
    console.error('获取预存总金额出错:', err);
    Message.error('获取预存总金额失败');
  }
}

// 获取运营商列表
async function fetchPartnerList() {
  partnerLoading.value = true;
  try {
    const params = {
      status: 1, // 只查询启用状态的运营商
      size: 1000 // 查询足够多的记录以覆盖所有运营商
    };
    const res = await getPartnerList(params);
    partnerOptions.value = res.data.records;
  } catch (err) {
    console.error('获取运营商列表出错:', err);
    Message.error('获取运营商列表失败');
  } finally {
    partnerLoading.value = false;
  }
}

// 搜索
function search() {
  if (timeRange.value && timeRange.value.length === 2) {
    searchForm.startTime = dayjs(timeRange.value[0]).format('YYYY-MM-DD HH:mm:ss');
    searchForm.endTime = dayjs(timeRange.value[1]).format('YYYY-MM-DD HH:mm:ss');
  } else {
    searchForm.startTime = undefined;
    searchForm.endTime = undefined;
  }
  
  pagination.current = 1;
  fetchData();
  fetchDepositSum();
}

// 重置
function reset() {
  searchForm.partnerId = undefined;
  searchForm.incomeStatus = undefined;
  searchForm.startTime = undefined;
  searchForm.endTime = undefined;
  timeRange.value = undefined;
  
  search();
}

// 分页变化
function onPageChange(current: number) {
  pagination.current = current;
  fetchData();
}

// 每页条数变化
function onPageSizeChange(pageSize: number) {
  pagination.pageSize = pageSize;
  fetchData();
}

// 打开新增预存表单
function openAddForm() {
  addFormVisible.value = true;
}

// 打开预存消费表单
function openConsumeForm() {
  consumeFormVisible.value = true;
}

// 关闭表单
function closeForm() {
  if (addFormRef.value) {
    addFormRef.value.resetForm();
  }
  if (consumeFormRef.value) {
    consumeFormRef.value.resetForm();
  }
}

// 提交新增预存表单
async function handleSubmitForm(done: (closed: boolean) => void) {
  if (!addFormRef.value) {
    done(false);
    return;
  }
  
  try {
    // 直接使用表单组件暴露的validate方法
    const valid = await addFormRef.value.validate();
    if (!valid) {
      done(false);
      return;
    }
    
    const values = {
      partnerId: addFormRef.value.form.partnerId,
      amount: addFormRef.value.form.amount,
      remark: addFormRef.value.form.remark
    };
    
    const res = await addPartnerDeposit({
      partnerId: values.partnerId,
      amount: values.amount,
      remark: values.remark,
    });
    
    if (res.data) {
      Message.success('新增预存成功');
      done(true);
      addFormVisible.value = false;
      fetchData();
      fetchDepositSum();
    } else {
      Message.error('新增预存失败');
      done(false);
    }
  } catch (error) {
    console.error('新增预存出错:', error);
    Message.error('新增预存失败');
    done(false);
  }
}

// 提交预存消费表单
async function handleSubmitConsumeForm(done: (closed: boolean) => void) {
  if (!consumeFormRef.value) {
    done(false);
    return;
  }
  
  try {
    // 直接使用表单组件暴露的validate方法
    const valid = await consumeFormRef.value.validate();
    if (!valid) {
      done(false);
      return;
    }
    
    const values = {
      partnerId: consumeFormRef.value.form.partnerId,
      amount: consumeFormRef.value.form.amount,
      sn: consumeFormRef.value.form.sn,
      remark: consumeFormRef.value.form.remark
    };
    
    const res = await consumePartnerDeposit({
      partnerId: values.partnerId,
      amount: values.amount,
      sn: values.sn,
      remark: values.remark,
    });
    
    if (res.data) {
      Message.success('预存消费成功');
      done(true);
      consumeFormVisible.value = false;
      fetchData();
      fetchDepositSum();
    } else {
      Message.error('预存消费失败');
      done(false);
    }
  } catch (error) {
    console.error('预存消费出错:', error);
    Message.error('预存消费失败');
    done(false);
  }
}

// 处理审核
async function handleAudit(record: PartnerIncome, status: number) {
  Modal.confirm({
    title: status === IncomeStatusEnum.APPROVED ? '审核通过' : '审核拒绝',
    content: '确定要执行此操作吗？',
    onOk: async () => {
      try {
        const res = await auditPartnerIncome({
          id: record.id,
          status: status,
        });
        
        if (res.data) {
          Message.success('审核操作成功');
          fetchData();
          fetchDepositSum();
        } else {
          Message.error('审核操作失败');
        }
      } catch (error) {
        console.error('审核操作出错:', error);
        Message.error('审核操作失败');
      }
    },
  });
}

onMounted(() => {
  fetchPartnerList();
  fetchData();
  fetchDepositSum();
});
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px;
}

.summary-row {
  margin: 16px 0;
  padding: 20px;
  background-color: var(--color-fill-2);
  border-radius: 4px;
}
</style> 